package com.xingji.caixia.activity;

import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.xingji.caixia.Constant;
import com.xingji.caixia.MyApplication;
import com.xingji.caixia.MyService;
import com.xingji.caixia.R;
import com.xingji.caixia.camera.CameraInterface;
import com.xingji.caixia.entitys.CardDao;
import com.xingji.caixia.entitys.UploadData;
import com.xingji.caixia.entitys.dataType;
import com.xingji.caixia.fragment.DataFragment;
import com.xingji.caixia.fragment.MainFragment;

import org.xutils.ex.DbException;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;

public class MainActivity extends BaseActivity implements MainFragment.OnFragmentInteractionListener,DataFragment.OnFragmentInteractionListener {

    private FrameLayout content;
    private MainFragment mainFragment;
    private DataFragment dataFragment;
    private FragmentManager manager;
    private MainActivity self = MainActivity.this;
    private String school_id;
    private Integer unUpload = 0;   //未上传内容计数
    private String unUploadString = "";
    private Boolean threadFlag = true;
    boolean suspended=false;
    Boolean isDataFragment = false;

    ProgressDialog progress ;

    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM月dd日 EE HH:mm");

    @ViewInject(R.id.time)
    TextView time;

    @ViewInject(R.id.name)
    TextView name;

    @ViewInject(R.id.setting)
    ImageView setting;
    private ChangeTimeRunable changeTimeRunable;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        x.view().inject(this);
        Intent intent = new Intent(self,MyService.class);
        bindService(intent,connection,BIND_AUTO_CREATE);
        school_id = getIntent().getStringExtra("school_id");
        content = (FrameLayout) findViewById(R.id.content);
        mainFragment = MainFragment.newInstance(school_id);
        dataFragment = DataFragment.newInstance(null);
        manager = getSupportFragmentManager();
        manager.beginTransaction()
                .add(R.id.content,mainFragment)
                .add(R.id.content,dataFragment)
                .hide(dataFragment)
                .commit();

        BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.navigation);
        navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
        changeTimeRunable = new ChangeTimeRunable();
        new Thread(changeTimeRunable).start();

        try {
            unUpload = CardDao.getCards(dataType.UNPLOAD).size();
        } catch (DbException e) {
            e.printStackTrace();
        }

        LinearLayout sugar = (LinearLayout) findViewById(R.id.sugar);
        sugar.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View view) {
                Toast.makeText(self,"当前版本:"+ MyApplication.getInstance().getVersionName(),Toast.LENGTH_SHORT).show();
                return false;
            }
        });

        progress = new ProgressDialog(self);
    }



    class ChangeTimeRunable implements Runnable {

        @Override
        public void run() {
            while (threadFlag){
                mHandler.sendEmptyMessage(1);
                try {
                    Thread.sleep(30000);
                    synchronized (this){
                        while (suspended){
                            wait();
                        }
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }

        public void pause(){
            suspended = true;
        }

        public synchronized void myresume(){
            suspended = false;
            notify();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    public void onSetting(View view){
        AlertDialog.Builder builder = new AlertDialog.Builder(self);
        builder.setMessage("确认清理?").setNegativeButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                mHandler.sendEmptyMessage(3);
            }
        }).setPositiveButton("下次",null).show();
    }

    @Override
    protected void onResume() {
        super.onResume();
        IntentFilter filter = new IntentFilter();
        filter.addAction(Constant.HAS_READ);
        filter.addAction(Constant.UNREAD);
        filter.addAction(Constant.ZERO_READ);
        registerReceiver(receiver,filter);
    }

    BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            Log.e("action",intent.getAction()+"");
            //// TODO: 2017/9/29  不考虑效率了先 能用就行。毕竟就这么点钱。艹
            if (intent.getAction().equals(Constant.HAS_READ)){
                unUpload --;
                if (unUpload<0)unUpload = 0;
            }
            if (intent.getAction().equals(Constant.UNREAD)){
                unUpload ++;
            }
            if (intent.getAction().equals(Constant.ZERO_READ)){
                unUpload = 0;
            }
            unUploadString = String.format(Locale.CHINA,"当前%d条未上传",unUpload);
            Log.e("unUploadString",unUploadString);
            if (isDataFragment){
                mHandler.sendEmptyMessage(2);
            }
        }
    };

    private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
            = new BottomNavigationView.OnNavigationItemSelectedListener() {

        @Override
        public boolean onNavigationItemSelected(@NonNull MenuItem item) {
            switch (item.getItemId()) {
                case R.id.navigation_home:
                    if (suspended){
                        changeTimeRunable.myresume();
                    }
                    isDataFragment = false;
                    manager.beginTransaction().show(mainFragment).hide(dataFragment).commit();
                    return true;
                case R.id.navigation_dashboard:
                    if (!suspended){
                        changeTimeRunable.pause();
                    }
                    isDataFragment = true;
                    mHandler.sendEmptyMessage(2);
                    manager.beginTransaction().hide(mainFragment).show(dataFragment).commit();
                    return true;
                case R.id.navigation_notifications:
                    new AlertDialog.Builder(self).setMessage("确定退出吗?")
                            .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialogInterface, int i) {
                                    getSharedPreferences("user", MODE_PRIVATE).edit().clear().apply();
                                    finish();
                                }
                            })
                            .setNegativeButton("取消",null)
                            .show();

                    return true;
            }
            return false;
        }

    };



    Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case 1:
                    final String date = simpleDateFormat.format(new Date().getTime());
                    time.setText(date);
                    break;
                case 2:
                    time.setText(unUploadString);
                    dataFragment.refreshUI();
                    break;
                case 3://清除缓存  删除已删除的记录和图片
                    progress.setMessage("清理中...");
                    progress.show();
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                List<UploadData> list = CardDao.getCards(dataType.UPLOADED);
                                for (UploadData data : list){
                                    if (data!=null){
                                        //删除图片
                                        File img = new File(data.getImgPath());
                                        if (img.isFile() && img.exists()){
                                            img.delete();
                                        }
                                        File tbImg = new File(data.getThumbImgPath());
                                        if (tbImg.isFile() && tbImg.exists()){
                                            tbImg.delete();
                                        }
                                        CardDao.deleteCache(data);
                                    }
                                }
                                Thread.sleep(1000);
                                mHandler.sendEmptyMessage(4);
                            } catch (DbException e) {
                                mHandler.sendEmptyMessage(4);
                                e.printStackTrace();
                            } catch (InterruptedException e) {
                                mHandler.sendEmptyMessage(4);
                                e.printStackTrace();
                            }
                        }
                    }).start();
                    break;
                case 4:
                    progress.dismiss();
                    break;
            }
        }
    };

    @Override
    protected void onPause() {
        super.onPause();
        unregisterReceiver(receiver);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbindService(connection);
        CameraInterface.getInstance().doStopCamera();
    }

    @Override
    public void onFragmentInteraction(Uri uri) {
        Log.e("uri",uri.toString());
    }

    @Override
    public void setSchoolName(String name) {
        this.name.setText(name);
    }


    /**
     * service
     */
    public MyService myService;

    private ServiceConnection connection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            MyService.Mybinder mybinder = (MyService.Mybinder) iBinder;
            myService = mybinder.getService();
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            Log.e("componentName",componentName.toString());
        }
    };
}
